package com.rabbit.icore;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Auther:
 * @Date:
 * @company：CTTIC
 */
@Component
@Slf4j
public class Queues {

    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.queueUrl}")
    private String url;


    /**
     * 根据API获得指定virtual host 的所有队列名称
     * @return
     */
    public Map<String, List<String>> getQueueArray() {
        HttpGet httpPost = new HttpGet(url);
        CloseableHttpClient pClient = getBasicHttpClient();
        CloseableHttpResponse response = null;
        JSONArray jsonArray = null;
        HashMap<String, List<String>> map = new HashMap<>();
        List addQueueList = new ArrayList();
        List reduceQueueList = new ArrayList();
        try {
            response = pClient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                String string = EntityUtils.toString(response.getEntity());
                jsonArray = (JSONArray) JSONObject.parse(string);
                if (null != jsonArray) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String name = (String) jsonArray.getJSONObject(i).get("name");
                        if (name.contains("add")){
                            addQueueList.add(name);
                        }else if (name.contains("reduce")){
                            reduceQueueList.add(name);
                        }
                    }
                    map.put("add",addQueueList);
                    map.put("reduce",reduceQueueList);
                }
            } else {
                System.out.println("请求返回:" + state + "(" + url + ")");
            }
        } catch (Exception e) {
            log.error("地址url:" + url + "，异常：" + e.toString());
        } finally {
            closeAll(response, pClient);
        }
        return map;
    }

    private void closeAll(CloseableHttpResponse response, CloseableHttpClient pClient) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            pClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private CloseableHttpClient getBasicHttpClient() {
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 设置BasicAuth
        CredentialsProvider provider = new BasicCredentialsProvider();
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
        return httpClientBuilder.build();
    }
}
